#include <51func.h>
int main(int argc, char *argv[])
{
    // ./3_azhen 192.168.118.128 1234
    ARGS_CHECK(argc,3);
    // socket
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(atoi(argv[2]));
    serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
    // setsockopt
    int arg = 1; // REUSEADDR的参数值为真
    int ret = setsockopt(sockfd,SOL_SOCKET,
                         SO_REUSEADDR,&arg,sizeof(arg));
    ERROR_CHECK(ret,-1,"setsockopt");
    // bind
    ret = bind(sockfd,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
    ERROR_CHECK(ret,-1,"bind");
    // listen
    listen(sockfd,10);
    char buf[4096];
    // 为两个集合申请内存
    fd_set monitorset; //监听集合
    fd_set readyset; // 就绪集合
    FD_ZERO(&monitorset);
    FD_SET(sockfd,&monitorset);
    int netfd = -1; // netfd如果数值为-1，则未建立连接
    while(1){
        memcpy(&readyset,&monitorset,sizeof(fd_set));
        select(100,&readyset,NULL,NULL,NULL);
        if(FD_ISSET(sockfd,&readyset)){
            netfd = accept(sockfd,NULL,NULL);
            printf("client is connected!\n");
            // 增加netfd和stdin的监听，移除sockfd的监听
            FD_SET(netfd,&monitorset);
            FD_SET(STDIN_FILENO,&monitorset);
            FD_CLR(sockfd,&monitorset);
        }
        if(netfd!=-1 && FD_ISSET(netfd,&readyset)){
            bzero(buf,sizeof(buf));
            ssize_t sret = recv(netfd,buf,sizeof(buf),0);
            if(sret == 0){
                // 阿强主动退出
                FD_SET(sockfd,&monitorset);
                FD_CLR(netfd,&monitorset);
                FD_CLR(STDIN_FILENO,&monitorset);
                close(netfd);
                netfd = -1;
                printf("jianqiang!\n");
            }
            printf("buf = %s\n", buf);
        }
        if(FD_ISSET(STDIN_FILENO,&readyset)){
            bzero(buf,sizeof(buf));
            ssize_t sret = read(STDIN_FILENO,buf,sizeof(buf));
            if(sret == 0){
                // 阿珍踢人
                FD_SET(sockfd,&monitorset);
                FD_CLR(netfd,&monitorset);
                FD_CLR(STDIN_FILENO,&monitorset);
                close(netfd);
                netfd = -1;
                printf("xixi\n");
            }
            send(netfd,buf,strlen(buf),0);
        }
    }
    return 0;
}

